# coding:utf-8
import hashlib
import os
import time
import requests
import MySQLdb


def push_comurl():
    '''
    获取数据库的cid
    :return:
    '''
    db = MySQLdb.connect(host='172.20.18.27', port=3306, user='seoadmin',
                         passwd='JQExGE2YKe5', db='seocompany', charset='utf8')
    cur = db.cursor()
    file_name = 'comurl0_%s.txt'%(time.time())
    # file_name = 'comurl0.txt'
    num = 0
    cid_data = []  # cid  数组
    urls = []     #  URL 数组
    files = [file_name]
    sql = "SELECT i.cid FROM company_{0} AS i WHERE unix_timestamp(now()) - addtime < 300"
    for i in range(0, 200):
        cur.execute(sql.format(i))
        data = cur.fetchall()
        for i in data:
            cid_data.append(i[0])
    for i in cid_data:
        cid = str(i)
        skey = cid + '$5*gongchang.com工厂网'
        m = hashlib.md5()
        m.update(skey)
        jmcid = cid+ "-" + m.hexdigest()[4:8]
        comurl = "https://company.ch.gongchang.com/qiye%s/" % jmcid
        urls.append(comurl)
        num +=1
        print num
        if (num % 2000 == 0):
            with  open(file_name,'a') as f:
                f.write('\n'.join(urls))
            urls =[]
            file_name = './comurl_%s_%s.txt' % (str(num),time.time())
            # file_name = './comurl_%s.txt' % str(num)
            files.append(file_name)
    if urls:
        with open(file_name,'a') as f:
            f.write('\n'.join(urls))
    cur.close()
    db.close()
    url = "/urls?site=company.ch.gongchang.com&token=W1OQD12hHPMw9UJP"
    for i in files:
     filecontents = {"file": open(i,"rb")}
     r = requests.post("http://data.zz.baidu.com" + url, files=filecontents)
     baiduresult = "推送结果%s \n" % (r.text).encode('utf-8')
     print  baiduresult
     os.remove(i)


if __name__=="__main__":

    while True:
        push_comurl()
        time.sleep(300)
